package com.ash.print;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;

import javax.swing.*;
import java.awt.*;
import java.awt.font.FontRenderContext;
import java.awt.font.TextAttribute;
import java.awt.image.BufferedImage;
import java.text.AttributedCharacterIterator;
import java.text.AttributedString;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class SpuTemplatePreview {

    public static void main(String[] args) {
        // 假设的纸张尺寸和分辨率
        int width = (int) Math.round(76 * 2.8346);
        int height = (int) Math.round(130 * 2.8346);

        // 创建一个BufferedImage作为预览画布
        BufferedImage previewImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        // 获取Graphics2D对象以在BufferedImage上绘制
        Graphics2D g2d = previewImage.createGraphics();

        FontMetrics fontMetrics = g2d.getFontMetrics();


        // 设置背景色（可选）
        g2d.setColor(Color.WHITE);
        g2d.fillRect(0, 0, width, height);

        g2d.setStroke(new BasicStroke(2f)); // 边框宽度为2个单位

        // 绘制边框
        g2d.setColor(Color.black);

        g2d.drawString("商品码", 85, 20);

        g2d.drawLine(5, 30, width - 15, 30);


        g2d.drawString("SPU码：", 20, 45);


        String spuName = "商品名称：" + "test123456789-123456789";

        String[] lineNum = wrapText(spuName, (float) (width - 45), fontMetrics);

        int baseY = 65;
        for (int i = 0; i < lineNum.length; i++) {
            g2d.drawString(lineNum[i], 20, baseY + 15 * i);
        }

        baseY = baseY + 15 * (lineNum.length);


        String skuAttr = "商品规格：" + "123456789-123456789";
        String[] skuAttrLineNum = wrapText(skuAttr, (float) (width - 45), fontMetrics);

        for (int i = 0; i < skuAttrLineNum.length; i++) {
            g2d.drawString(skuAttrLineNum[i], 20, baseY + 15 * i);
        }

        baseY = baseY + 15 * (skuAttrLineNum.length - 1);

        g2d.drawLine(5, baseY + 20, width - 15, baseY + 20);

        g2d.drawString("用户名：" , 20, baseY + 40);
        g2d.drawString("国家：" , 20, baseY + 60);
        g2d.drawString("货架号：" , 20, baseY + 80);

        g2d.drawLine(5, baseY + 100, width - 15, baseY + 100);

        g2d.drawString("操作员：", 20, baseY + 120);
        g2d.drawString("分拣日期：", 20, baseY + 140);

        g2d.drawRect(5, 5, width - 20, baseY + 160);

        // 关闭Graphics2D对象
        g2d.dispose();

        // 使用JLabel和JFrame显示预览图像
        JLabel label = new JLabel(new ImageIcon(previewImage));
        JFrame frame = new JFrame("Print Preview");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(label);
        frame.pack();
        frame.setVisible(true);
    }

    /**
     * 根据指定宽度将文本分割成多行。
     *
     * @param text  文本迭代器
     * @param width 每行的最大宽度
     * @return 分割后的文本行数组
     */
    private static String[] wrapText(String text, float width, FontMetrics fontMetrics) {
        StringBuilder wrappedText = new StringBuilder();
        String currentLine = "";
        float lineWidth = 0;
        char lastChar = '\n';

        for (int i = 0; i < text.length(); i++) {
            char c = text.charAt(i);
            int charWidth = fontMetrics.charWidth(c);
            if (c == ' ' || c == '\n') {
                if (lineWidth + charWidth >= width) {
                    wrappedText.append(currentLine.trim()).append('\n');
                    currentLine = "";
                    lineWidth = 0;

                } else {
                    if (!currentLine.isEmpty()) {
                        currentLine += ' ';
                    }
                    lineWidth += charWidth;
                }
            } else {
                if (lastChar != ' ' && lineWidth + charWidth > width) {
                    wrappedText.append(currentLine.trim()).append('\n');
                    currentLine = "" + c;
                    lineWidth = charWidth;
                } else {
                    currentLine += c;
                    lineWidth += charWidth;
                }
            }

            lastChar = c;
        }

        if (!currentLine.isEmpty()) {
            wrappedText.append(currentLine.trim());
        }

        return wrappedText.toString().split("\n");
    }
}
